<template>
  <div v-loading="loading" class="app-container uni-scroll" style="height: calc(100vh - 100px);">
    <div>
      <el-button-group>
        <el-button
          round
          type="primary"
          @click="searchWeek"
        >{{ $t('one')+$t('week') }}</el-button>
        <el-button
          type="primary"
          @click="searchMonth"
        >{{ $t('one')+$t('month') }}</el-button>
        <el-button
          type="primary"
          @click="search3month"
        >{{ $t('three')+$t('month') }}</el-button>
      </el-button-group>
      <el-date-picker
        v-model="startDate"
        type="datetime"
        :picker-options="pickerOptions1"
        value-format="timestamp"
      />
      <el-date-picker
        v-model="endDate"
        type="datetime"
        :picker-options="pickerOptions1"
        value-format="timestamp"
      />
      <el-button-group>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="listWithExplain"
        >{{ $t("search") }}</el-button>
      </el-button-group>
    </div>
    <div v-for="(item,index) in canvasList" :key="index" class="box-card">
      <template v-if=" showHidden === '1' || !item.hidden">
        <multi-line-chart
          style="height: 450px;margin-bottom: 13px;margin-left: 13px;width: 98%"
          :chart-data="item"
        />
      </template>
    </div>
    <div style="margin-top: 13px;margin-left: 25px">
      <el-switch
        v-model="filterRepeat"
        style=";margin-right: 5px"
        active-value="1"
        inactive-value="0"
        :active-text="$t('filter')+$t('repeat')"
        @change="filterRepeatChange"
      />
      <el-switch
        v-model="enableEval"
        active-value="1"
        inactive-value="0"
        :active-text="$t('enable')+$t('script')"
        @change="enableEvalChange"
      />
      <el-switch
        v-model="showHidden"
        active-value="1"
        inactive-value="0"
        :active-text="$t('show') + $t('hidden')"
        @change="showHiddenChange"
      />
    </div>
  </div>
</template>

<script>
import MultiLineChart from '@/components/Chart/MultiLineChart'
import {
  formatDate,
  failureNotice
} from '@/util/common'
import {
  getFilterRepeat,
  setFilterRepeat,
  getEnableEval,
  setEnableEval,
  getShowHidden,
  setShowHidden
} from '@/util/storage'
import { listWithExplain } from '@/api/iot/iotDeviceSensorDataApi'
import resize from '@/components/Mixins/resize'
export default {
  name: 'SensorAnalysis',
  components: {
    MultiLineChart
  },
  mixins: [resize],
  data() {
    return {
      multiLineData: {
        dataList: [],
        dateList: []
      },
      deviceName: null,
      canvasList: [],
      sensorId: null,
      deviceCore: null,
      startDate: '',
      endDate: '',
      pickerOptions1: {
        shortcuts: [
          {
            text: this.$t('today'),
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: this.$t('today'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: this.$t('a') + this.$t('week') + this.$t('ago'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      loading: false,
      filterRepeat: getFilterRepeat(),
      enableEval: getEnableEval(),
      showHidden: getShowHidden()
    }
  },
  mounted() {
    const param = this.$route.query
    this.sensorId = param.sensorId
    this.deviceCore = param.deviceCore
    this.deviceName = param.deviceName
    const timestamp = new Date().getTime()
    this.startDate = timestamp - 7 * 24 * 60 * 60 * 1000
    this.endDate = timestamp
    this.listWithExplain()
    this.setTagsViewTitle()
  },
  methods: {
    filterRepeatChange() {
      setFilterRepeat(this.filterRepeat)
      this.listWithExplain()
    },
    enableEvalChange() {
      setEnableEval(this.enableEval)
      this.listWithExplain()
    },
    showHiddenChange() {
      setShowHidden(this.showHidden)
    },
    setTagsViewTitle() {
      this.tempRoute = Object.assign({}, this.$route)
      const route = Object.assign({}, this.tempRoute, {
        title: `${this.deviceName}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    listWithExplain() {
      this.loading = true
      listWithExplain({
        sensorId: this.sensorId,
        startTime: Math.round(this.startDate / 1000),
        endTime: Math.round(this.endDate / 1000),
        enableEval: this.enableEval === '1',
        filterRepeat: this.filterRepeat === '1'
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          let explainList
          const dataList = data.dataList
          if (data.explainList != null) {
            explainList = data.explainList
          } else {
            failureNotice(this, this.$t('no') + this.$t('explain'))
            this.loading = false
            return
          }
          if (dataList.length === 0) {
            failureNotice(this, this.$t('no') + this.$t('data'))
            this.loading = false
          }
          /**
           * 装换时间
           */
          for (let i = 0; i < dataList.length; i++) {
            dataList[i].unixTimestamp = dataList[i].createdTime * 1000
            dataList[i].createdTime = formatDate(this, dataList[i].createdTime)
          }

          const canvasList = []
          const explainLastValueMap = {}
          for (let i = 0; i < explainList.length; i++) {
            const explain = explainList[i]

            if (explain.type === 'line') {
              const dy = []
              const dx = []

              let dataBean
              for (let j = 0; j < dataList.length; j++) {
                dataBean = dataList[j].val

                if (typeof (dataBean[explain.keyName]) !== 'undefined') {
                  explainLastValueMap[explain.keyName] = dataBean[explain.keyName]
                  dy.push({
                    val: dataBean[explain.keyName],
                    time: dataList[j].unixTimestamp
                  })
                } else {
                  dy.push({
                    val: explainLastValueMap[explain.keyName],
                    time: dataList[j].unixTimestamp
                  })
                }

                dx.push({
                  createdTime: dataList[j].createdTime,
                  unixTimestamp: dataList[j].unixTimestamp
                })
              }

              const a = dx[0].unixTimestamp
              const x = []
              const y = []
              const c = a - (86400000 - (a % 86400000))
              const firstDay0 = this.get0Time(c + 86400000)
              const firstDay24 = this.get0Time(c + 2 * 86400000)
              for (let k = 0; k < dx.length; k++) {
                if (dx[k].unixTimestamp > firstDay0) {
                  if (dx[k].unixTimestamp < firstDay24) {
                    x.push(this.xTime(dx[k].unixTimestamp))
                  } else {
                    break
                  }
                }
              }

              let dayPoint = 0
              let yDataTemp = []

              for (let j = 0; j < dy.length; j++) {
                if (dy[j].time < firstDay0) {
                  continue
                }
                if (dy[j].time < firstDay24 + dayPoint * 86400000) {
                  yDataTemp.push(dy[j].val)
                } else {
                  dayPoint++
                  const unixTimestamp = new Date(
                    firstDay24 + (dayPoint - 1) * 86400000
                  )
                  const commonTime =
                    unixTimestamp.getFullYear() +
                    '-' +
                    this.getzf(unixTimestamp.getMonth() + 1) +
                    '-' +
                    this.getzf(unixTimestamp.getDate())
                  y.push({
                    name: commonTime,
                    dataList: yDataTemp
                  })
                  yDataTemp = []
                }
              }

              canvasList.push({
                hidden: explain.hidden,
                title: explain.name + '(' + explain.unit + ')',
                dataList: y,
                dateList: x
              })
            }
          }
          this.canvasList = canvasList
        }
        this.loading = false
      })
    },
    get0Time(timestamp) {
      const date = new Date(timestamp)
      const times = date.getTime()
      const hour = date.getHours()
      const minute = date.getMinutes()
      const second = date.getSeconds()
      const dayTime = times - hour * 3600 * 1000 - minute * 60 * 1000 - second * 1000
      return dayTime
    },
    getzf(num) {
      if (parseInt(num) < 10) {
        num = '0' + num
      }
      return num
    },
    xTime(timestamp) {
      const date = new Date(timestamp)
      let hour = date.getHours()
      if (hour < 10) {
        hour = '0' + hour
      }
      let minute = date.getMinutes()
      if (minute < 10) {
        minute = '0' + minute
      }
      return hour + ':' + minute
    },
    search3month() {
      const timestamp = new Date().getTime()
      this.startDate = new Date().getTime() - 3 * 31 * 24 * 60 * 60 * 1000
      this.endDate = timestamp
      this.listWithExplain()
    },
    searchMonth() {
      const timestamp = new Date().getTime()
      this.startDate = new Date().getTime() - 31 * 24 * 60 * 60 * 1000
      this.endDate = timestamp
      this.listWithExplain()
    },
    searchWeek() {
      const timestamp = new Date().getTime()
      this.startDate = new Date().getTime() - 7 * 24 * 60 * 60 * 1000
      this.endDate = timestamp
      this.listWithExplain()
    }
  }
}
</script>
